package lingou.homework.postbar.controller;

import jakarta.servlet.http.HttpSession;
import lingou.homework.postbar.controller.proto.resp.ImageResponse;
import lingou.homework.postbar.controller.proto.resp.Response;
import lingou.homework.postbar.controller.tool.SessionHelper;
import lingou.homework.postbar.exception.BusinessException;
import lingou.homework.postbar.service.UserService;
import lingou.homework.postbar.tool.StaticURL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/file")
public class FileStoreController {

//    @PostMapping
//    Response upload(String path, @RequestBody MultipartFile file){
//        return null;
//    }
//    @GetMapping
//    Response download(String path){
//        return null;
//    }

    @Autowired
    UserService userService;

    @PostMapping("/post/image")
    ImageResponse uploadPostImage(MultipartFile file, HttpSession session) throws IOException {
        if(!SessionHelper.isLogin(session)) return ImageResponse.ofFailure(SessionHelper.NOT_LOGGED.getMsg());
        String name = StaticURL.saveToPool(file.getInputStream(), StaticURL.POST_POOL);
        return ImageResponse.ofSuccess(
//                "http://43.138.212.77:8880/file/post/image/" + name,
                "/file/post/image/" + name,
                null,
                null);
    }

    @GetMapping("/post/image/{name}")
    ResponseEntity<ByteArrayResource> downloadPostImage(@PathVariable String name, HttpSession session) throws IOException {
//        Long id = SessionHelper.getCurrentUser(session);
//        if (id == null) return null;
        ByteArrayResource byteArrayResource = new ByteArrayResource(StaticURL.getFromPool(StaticURL.POST_POOL, name).readAllBytes());
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=" + URLEncoder.encode("post_image", StandardCharsets.UTF_8))
                .body(byteArrayResource);
    }

    @PostMapping("/head")
    Response uploadHead(@RequestBody MultipartFile file, HttpSession session) throws Exception {
//        System.out.println(file.getName());
//        System.out.println(file.getOriginalFilename());
//        try {
//            System.out.println(new String(file.getBytes()));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        Long id = SessionHelper.getCurrentUser(session);
        if (id == null) return SessionHelper.NOT_LOGGED;
        StaticURL.saveToPool(file.getInputStream(), StaticURL.HEAD_POOL, id.toString());
        return Response.ofSuccess();
    }

//    @GetMapping("/head")
//    void downloadHead(Long userId, HttpSession session, HttpServletResponse response) {
//        Long id = SessionHelper.getCurrentUser(session);
//        if (id == null) response.;
//        if (userId == null) userId = id;
//        try {
//            IOUtils.copy(StaticURL.getUserHead(userId), response.getOutputStream());
//            response.setContentType("application/octet-stream");
//            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("head_" + userId, "UTF-8"));
////            response.setContentLengthLong();
////            response.setCharacterEncoding("UTF-8");
//        } catch (IOException e) {
//            throw new SystemException(e);
//        }
//    }

//    @GetMapping("/head")
//    ResponseEntity<InputStreamResource> downloadHead(Long userId, HttpSession session) throws FileNotFoundException {
//        Long id = SessionHelper.getCurrentUser(session);
////        if (id == null) return null;
//        if (userId == null) userId = id;
//        InputStreamResource isr = new InputStreamResource(StaticURL.getFromPool(StaticURL.HEAD_POOL, userId.toString()));
//        return ResponseEntity.ok()
//                .contentType(MediaType.APPLICATION_OCTET_STREAM)
//                .header("Content-disposition", "attachment; filename=" + URLEncoder.encode("head_" + userId, StandardCharsets.UTF_8))
//                .body(isr);
//    }

    @GetMapping("/head")
    ResponseEntity<ByteArrayResource> downloadHead(Long userId, HttpSession session) throws IOException {
        Long id = SessionHelper.getCurrentUser(session);
        if (id == null) return null;
        if (userId == null) userId = id;
        ByteArrayResource byteArrayResource = new ByteArrayResource(StaticURL.getFromPool(StaticURL.HEAD_POOL, userId.toString()).readAllBytes());
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=" + URLEncoder.encode("head_" + userId, StandardCharsets.UTF_8))
                .body(byteArrayResource);
    }

    @GetMapping("/identify")
    ResponseEntity<ByteArrayResource> getIdentifyImage(Long userId, HttpSession session) throws IOException {
        long current = SessionHelper.checkLogin(session);
        if (userId == null) userId = current;
        if (current == userId || userService.isManager(current)) {
            InputStream image = StaticURL.getFromPool(StaticURL.IDENTIFY_POOL, String.valueOf(userId));
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header("Content-disposition", "attachment; filename=" + URLEncoder.encode("identify_" + userId, StandardCharsets.UTF_8))
                    .body(new ByteArrayResource(image.readAllBytes()));
        }
        else throw BusinessException.NO_PERMISSION;
    }

}
